<template>
	<view class="navTabBox">
		<view class="longTab">
			<scroll-view scroll-x="true" style="white-space: nowrap; display: flex;" scroll-with-animation :scroll-left="tabLeft">
				<view class="longItem" :style='"width:"+isWidth+"px"' :data-index="index" :class="index===value?'click':''" v-for="(item,index) in list" :key="index" :id="'id'+index" @click="longClick(index)">{{item[itemKey] || item}}</view>
				<view class="underlineBox" :style='"transform:translateX("+isLeft+"px);width:"+isWidth+"px"'>
					<view class="underline"></view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'navTab',
		props: {
			list: {
				type: Array,
				default: []
			},
			itemKey:{
				type:String,
				default:"name"
			},
			value:{
				type:Number,
				default:0
			}
		},
		data() {
			return {
				isLeft: 0, //导航栏下划线位置
				isWidth: 0, //每个导航栏占位
				tabLeft:0
			};
		},
		created() {
			// 获取设备宽度
			uni.getSystemInfo({
				success:(e)=> {
					if(this.value.length<= 5 ){
						this.isWidth = e.windowWidth / this.value.length //宽度除以导航标题个数=一个导航所占宽度	
					} else {
						this.isWidth = e.windowWidth / 5
					}
				}
			});
		},
		watch:{
			value:'longClick'
		},
		methods: {
			// 导航栏点击
			longClick(index){
				if(this.list.length>5){
					this.tabLeft = (index-2) * this.isWidth;//自动跟随
				}
				this.isLeft = index * this.isWidth //设置下划线位置
				this.$emit('input',index);//设置导航点击了哪一个
			}
		}
	}
</script>

<style lang="scss">
	.navTabBox {
		font-size: 26rpx;
		width: 100%;
		color: #000;
		.click {
			color: red;
		}
		.longTab {
			width: 100%;
			.longItem{ 
				height: 100rpx; 
				display: inline-block;
				line-height: 100rpx;
				text-align: center;
			}
			.underlineBox {
				width: 20%;
				display: flex;
				align-content: center;
				justify-content: center;
				transition: .5s;
				.underline {
					width: 80%;
					height: 2px;
					background-color: red;
				}
			}
		}
	}
</style>
